//
//  WXWalletModule.m
//  axc
//
//  Created by 郑江荣 on 2019/2/17.
//  Copyright © 2019 郑江荣. All rights reserved.
//

#import "WXWalletModule.h"
#import "farwolf.h"
#import "farwolf_weex.h"
#import "ZipDownloader.h"

@implementation WXWalletModule
@synthesize weexInstance;

WX_EXPORT_METHOD_SYNC(@selector(isExist))
WX_EXPORT_METHOD_SYNC(@selector(read))
WX_EXPORT_METHOD_SYNC(@selector(create:))
WX_EXPORT_METHOD(@selector(download:callback:))
-(BOOL)isExist{
    
    NSString *p=[self getPath];
    if( [p isExist])
        return true;
    else
        return false;
    
}
//-(void)isExist:(WXModuleCallback)callback{
//
//    NSString *p=[self getPath];
//    BOOL b=[p isExist];
//    callback(@{@"exist":@(b)});
//
//}
-(NSString*)read{
    if(![self isExist]){
        return @"";
    }
    NSURL *url= [NSURL fileURLWithPath:[self getPath]];
    NSError *err;
   
   NSString *str =[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&err];
    return str;
}
-(NSString*)create:(NSString*)content{
    NSFileManager *manager = [NSFileManager defaultManager];
   NSData *data =[content dataUsingEncoding:NSUTF8StringEncoding];
   [manager createFileAtPath:[self getPath] contents:data attributes:nil];
    return  [PREFIX_SDCARD add:[self getPath]];
}
-(NSString*)getPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    path=[path add:@"/wallet"];
    if(![path isExist]){
        [path mkdir];
    }
     path=[path add:@"/m.cer"];
    
    return path;
}
-(void)download:(NSString*)url callback:(WXModuleCallback)callback{
    
    NSString *path=[self getPath];
    if([path isExist]){
        [path delete];
    }
    ZipDownloader *zip= [[ZipDownloader alloc] initWidthUrl:url path:[self getPath] progress:^(float p,NSInteger current,NSInteger total) {
       
    } compelete:^(NSString *path) {
        callback(@{@"err":@(0)});
        
    } exception:^(NSError *err) {
          callback(@{@"err":@(1)});
    }];
    
    [zip start];
}
@end
